import "./css/index.less";

import Food from "./js/Food";
import ScorePanel from "./js/ScorePanel";
import Snake from "./js/Snake";



class GameControl {
  snake: Snake = new Snake();
  food: Food = new Food();
  scorePanel: ScorePanel = new ScorePanel();
  timer: NodeJS.Timer = setInterval(() => {}, 1000000);
  count: number = 0;

  constructor() {
    this.food.change(this.snake);
  }

  startGame(): void {
    document.addEventListener("keydown", (e) => this.keydownHandler(e));
    this.timer = setInterval(() => {
      this.count += 10;
      // 蛇的移动速度
      if (this.count % (200 - 10 * this.scorePanel.level) != 0)  return;
      // 如果蛇死亡则游戏结束
      if (! this.snake.isLife) return this.gameOver();
      this.snake.run();
      this.snake.eat(this.food) ? this.scorePanel.score++ : void 0;
    }, 10);
    
  }
  // 游戏结束
  gameOver(): void {
    clearInterval(this.timer);
    options.style.display = "flex";
  }

  keydownHandler(event: KeyboardEvent): void {
    let direction: string = this.snake.direction;
    let newDirection: string = event.key;

    // 排除不合法的方向
    if (direction == "ArrowUp" && newDirection == "ArrowDown") return;
    if (direction == "ArrowDown" && newDirection == "ArrowUp") return;
    if (direction == "ArrowLeft" && newDirection == "ArrowRight") return;
    if (direction == "ArrowRight" && newDirection == "ArrowLeft") return;

    
    this.snake.direction = newDirection;
    
  }
}

let start: HTMLElement = document.querySelector<HTMLElement>("#start") !;
let end: HTMLElement = document.querySelector<HTMLElement>("#end") !;
let options: HTMLElement = document.querySelector<HTMLElement>("#options") !;
let gameControl = new GameControl();

// 开始游戏
start.onclick = () => {
  gameControl.startGame();
  start.style.display = "none";
  end.style.display = "block";
  options.style.display = "none";
}
